import { createDiscreteApi } from 'naive-ui'
const { message } = createDiscreteApi(['message'])

export const formatTime = (time: number, withMs: boolean = true) => {
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  const milliseconds = String(date.getMilliseconds()).padStart(3, '0')
  if (withMs) {
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`
  } else {
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
}

export const copyText = (text: string) => {
  navigator.clipboard.writeText(text)
  message.success('复制成功')
}

/**
 * 将时间戳转换成n年前，n月前，n天前，n小时前，n分钟前，n秒前的格式
 * @param timestamp 时间戳
 * @returns 转换后的时间字符串
 */
export const fromNow = (timestamp?: number): string => {
  if (!timestamp) return ''
  const desTime = timestamp ? new Date(timestamp) : new Date()
  const currentTime = new Date().getTime()
  const timeDiff = currentTime - desTime.getTime()
  if (timeDiff < 60 * 1000) {
    return `${Math.floor(timeDiff / 1000)}秒前`
  } else if (timeDiff < 60 * 60 * 1000) {
    const minutes = Math.floor(timeDiff / (60 * 1000))
    return `${minutes}分钟前`
  } else if (timeDiff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(timeDiff / (60 * 60 * 1000))
    return `${hours}小时前`
  } else if (timeDiff < 30 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(timeDiff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  } else if (timeDiff < 12 * 30 * 24 * 60 * 60 * 1000) {
    const months = Math.floor(timeDiff / (30 * 24 * 60 * 60 * 1000))
    return `${months}月前`
  } else {
    const years = Math.floor(timeDiff / (12 * 30 * 24 * 60 * 60 * 1000))
    return `${years}年前`
  }
}
